package edu.hncj.seckill.controller;

import edu.hncj.seckill.domain.Business;
import edu.hncj.seckill.response.Result;
import edu.hncj.seckill.service.BusinessService;
import edu.hncj.seckill.service.SmsSerive;
import edu.hncj.seckill.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gcl
 */
@CrossOrigin
@Controller
@RequestMapping("/business")
public class BusinessController {

    @Value("${business.id}")
    private String businessid;

    @Autowired
    BusinessService businessService;

    @Autowired
    SmsSerive smsSerive;

    /**
     * 检查商家登录名
     * @param loginname 登录名
     * @return 返回提示结果
     */
    @ResponseBody
    @RequestMapping("/checkloginname")
    public String checkloginname(@RequestParam(name = "loginname")String loginname) {
        Business business = businessService.seletByLoginName(loginname);
        return business == null ? "true" : "false";
    }


    /**
     * 检查店铺名称
     * @param businessname 店铺名称
     * @return 返回提示结果
     */
    @ResponseBody
    @RequestMapping("/checkbusinessname")
    public String checkbusinessname(@RequestParam(name = "businessname")String businessname) {
        Business business = businessService.seletByBusinessName(businessname);
        return business == null ? "true" : "false";
    }


    /**
     * 前端传入的手机号
     * @param telPhone 商家手机号注册
     * @return 返回提示结果
     */
    @ResponseBody
    @RequestMapping("/telephone")
    public Result telephone(@RequestParam(name = "telPhone")String telPhone) throws Exception {
        // 整理拿着手机号去数据库查询是否已经存在如果不存在就算了，如果存在就返回提示
        Business business = businessService.seletByPhoneNumber(telPhone);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (business == null){
            // 确认数据库中没有这个手机号就发送短信给该手机,并对返回结果进行解析识别其是否发送成功
            String ms = smsSerive.sendSms(telPhone, "相关");
            System.out.println(ms);
            String flag = "smsId";
            if (ms.contains(flag)){
                map.put("code",18);
                map.put("ms","验证码已发送,请注意查看!");
            }else{
                map.put("code",19);
                map.put("ms","验证码发送失败,请稍后再试!");
            }
        }else{
            map.put("code",17);
            map.put("ms","该手机号已经被注册，请直接登录！");
        }
        return Result.create(map);
    }


    /**
     * 验证短信码同时注册商家
     * @param loginName 登录名
     * @param businessName 店铺名称
     * @param password 密码
     * @param phone_number 用户正在注册的手机号
     * @param code 验证码
     * @return 返回提示结果
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @ResponseBody
    @RequestMapping("/signup")
    public Result regUser(@RequestParam(name = "loginname")String loginName,@RequestParam(name = "businessname")String businessName,@RequestParam(name = "password")String password,@RequestParam(name = "phone_number")String phone_number,@RequestParam(name = "code")String code) throws Exception {
        // 先对用户输入的验证码校验
        String ms = smsSerive.checkCode(phone_number, code);
        System.out.println(ms);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        String flag = "ok";
        if (ms.contains(flag)){
            // 可以认为验证通过,准备进行注册了
            // 整理拿着手机号去数据库查询是否已经存在如果不存在就算了，如果存在就返回提示
            Business business = businessService.seletByPhoneNumber(phone_number);
            // 如果确认无注册记录,就开始注册了
            if (business == null){
                // 创建存储对象
                Business business1 = new Business();
                // 放值已有属性
                business1.setLoginName(loginName);
                business1.setUserName(businessName);
                business1.setPhonenumber(phone_number);
                // 性别先设置为未知
                business1.setSex("2");
                // 生成随机salt
                String userSalt = Md5Utils.getSalt();
                business1.setSalt(userSalt);
                System.out.println(password);
                // 准备插入密码
                String tempStr = business1.getLoginName() + password + userSalt;
                String md5Password = DigestUtils.md5DigestAsHex(tempStr.getBytes());
                System.out.println(md5Password);
                business1.setPassword(md5Password);
                // 设置其他参数
                // 用户类型（00系统用户 01注册用户）
                business1.setUserType("01");
                // 帐号状态（0正常 1停用）
                business1.setStatus("0");
                business1.setDelFlag("0");
                business1.setCreateBy("admin");
                business1.setCreateTime(new Date());
                // 准备插入用户数据
                int u = businessService.insertBusiness(business1);
                if (u != 1){
                    map.put("code",24);
                    map.put("ms","发生未知错误,请您稍后再试！");
                    return Result.create(map);
                }
                // 通过手机号查询对象
                Business business2 = businessService.seletByPhoneNumber(phone_number);
                System.out.println(business2.getUserId());
                // 用户插入权限表
                int p = businessService.insertBusinessRole(business2.getUserId().toString(),businessid);
                if (p != 1){
                    map.put("code",25);
                    map.put("ms","发生未知错误,请您稍后再试！");
                    return Result.create(map);
                }else{
                    map.put("code",23);
                    map.put("ms","注册成功,正在跳转登录！");
                    return Result.create(map);
                }
            }else {
                map.put("code",21);
                map.put("ms","该手机号已经被注册，请直接登录！");
                return Result.create(map);
            }
        }else{
            map.put("code",20);
            map.put("ms","您短信验证码不正确!");
        }
        return Result.create(map);
    }


    @ResponseBody
    @RequestMapping(value="/getphone")
    public Result getOrder(@RequestParam("bid")String bid){
        // 常见返回集合
        Map<String,Object> map = new HashMap<String, Object>();
        // 通过id查询订单对象
        Business business = businessService.seletByID(bid);
        map.put("code", 36);
        map.put("data", business.getPhonenumber());
        map.put("msg", "查询成功");
        return Result.create(map);
    }



}
